//
//  CK_MenuViewController.m
//  MenuDemo
//
//  Created by lanou3g on 16/4/14.
//  Copyright © 2016年 liu. All rights reserved.
//

#import "CK_MenuViewController.h"
//#import "CK_LeftViewController.h"
#import "LCYUserInfoManager.h"
#import "LCYLoginViewController.h"

///抽屉展开的程度
#define kMenuLeftWidth [UIScreen mainScreen].bounds.size.width * 0.7

@interface CK_MenuViewController ()<UITableViewDataSource,UITableViewDelegate>

///默认左侧tableView
@property (nonatomic,strong) UITableView *leftTableView;
@property (nonatomic,assign) NSInteger index;

@property (nonatomic,strong) UIView *footerView;

@end

@implementation CK_MenuViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panMenuWithPanGesture:)];
    [self.view addGestureRecognizer:pan];
    
    
    self.menuArray = [NSMutableArray array];
}
#pragma mark - 添加手势
// 静态变量保存初始状态
static CGPoint begin;
static CGAffineTransform transform;
- (void)panMenuWithPanGesture:(UIPanGestureRecognizer *)pan {
    /// 位移量
    CGPoint translatePoint = CGPointZero;
    // 开始手势时的位置
    if (pan.state == UIGestureRecognizerStateBegan) {
        begin = [pan locationInView:self.view];
        transform = self.centerViewController.view.transform;
    }
    // 手势过程中的位置
    if (pan.state == UIGestureRecognizerStateChanged) {
        CGPoint end = [pan locationInView:self.view];
        translatePoint = CGPointMake(end.x - begin.x, 0);
    }
    // 手势结束时的位置
    if (pan.state == UIGestureRecognizerStateCancelled || pan.state == UIGestureRecognizerStateEnded) {
        if ([pan velocityInView:self.view].x > 0) {
            // 动画设置动画时长
            [self showLeftViewController:0.13];
        }else {
            [self hideLeftViewController:0.13];
        }
        return;
    }
    // 手势过程中，对视图进行位移
    if(self.centerViewController.view.transform.tx >= 0 && self.centerViewController.view.transform.tx <= kMenuLeftWidth) {
        self.centerViewController.view.transform = CGAffineTransformTranslate(transform, translatePoint.x, 0);
        self.leftViewController.view.transform = CGAffineTransformTranslate(transform,translatePoint.x, 0);
        self.leftTableView.transform = CGAffineTransformTranslate(transform, translatePoint.x, 0);
    }
}

#pragma mark - 判断当前菜单是否展开
- (BOOL)isShowing {
    if (self.centerViewController.view.transform.tx > 0) {
        return YES;
    } else {
        return NO;
    }
}

#pragma mark - 初始化方法
static CK_MenuViewController *CK_MenuVC = nil;
+ (instancetype)instanceWithLeftViewController:(UIViewController *)leftVC CenterViewController:(UIViewController *)centerVC {
    @synchronized(self) {
        if (!CK_MenuVC) {
            CK_MenuVC = [[CK_MenuViewController alloc]init];
            //设置window的rootViewController
            [UIApplication sharedApplication].keyWindow.rootViewController = CK_MenuVC;
            //设置属性
            CK_MenuVC.leftViewController = leftVC;
            CK_MenuVC.centerViewController = centerVC;
            //添加子视图控制器和子视图
            if (leftVC) {
                [CK_MenuVC addChildViewController:leftVC];
                [CK_MenuVC.view addSubview:leftVC.view];
            } else {
//                [CK_MenuVC setupLeftViewController];
                [CK_MenuVC setupLeftTableView];
            }
            if (centerVC) {
                [CK_MenuVC addChildViewController:centerVC];
                [CK_MenuVC.view addSubview:centerVC.view];
            }
        }
    }
    return CK_MenuVC;
}

#pragma mark - 获取抽屉的方法
+ (instancetype)getMenuViewController {
    return CK_MenuVC;
}
#pragma mark - 抽屉的展开和关闭
//展示左侧菜单
- (void)showLeftViewController {
    //动画展开
    [self showLeftViewController:0.7];
}
- (void)showLeftViewController:(CGFloat)duration{
    [UIView animateWithDuration:duration animations:^{
        self.centerViewController.view.transform = CGAffineTransformMakeTranslation(kMenuLeftWidth, 0);
        self.leftViewController.view.transform = CGAffineTransformMakeTranslation(kMenuLeftWidth, 0);
        self.leftTableView.transform = CGAffineTransformMakeTranslation(kMenuLeftWidth, 0);
    }];

}
//关闭左侧菜单
- (void)hideLeftViewController {
    //动画关闭
    [self hideLeftViewController:0.7];
}
- (void)hideLeftViewController:(CGFloat)duration {
    [UIView animateWithDuration:duration animations:^{
        self.centerViewController.view.transform = CGAffineTransformMakeTranslation(0, 0);
        self.leftViewController.view.transform = CGAffineTransformMakeTranslation(0, 0);
        self.leftTableView.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 默认的菜单视图tableView
- (void)setupLeftTableView {
    self.leftTableView = [[UITableView alloc]initWithFrame:CGRectMake(-kMenuLeftWidth, 0, kMenuLeftWidth, self.view.frame.size.height) style:UITableViewStylePlain];
    //设置数据源
    self.leftTableView.dataSource = self;
    //代理
    self.leftTableView.delegate = self;
    [self.view addSubview:self.leftTableView];
    
    
    self.leftTableView.backgroundColor = [UIColor blackColor];
    self.leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.leftTableView.scrollEnabled = NO;
    
    [self createFooterView];
}

- (void)createFooterView {
    self.footerView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 70, kMenuLeftWidth, 70)];
    [self.leftTableView addSubview:self.footerView];
}
#pragma mark - menuArray的setter方法
- (void)setMenuArray:(NSMutableArray *)menuArray {
    if (_menuArray != menuArray) {
        _menuArray = nil;
        _menuArray = menuArray;
        [self.leftTableView reloadData];
    }
}

#pragma mark - UITableViewDataSource
///数据源代理方法
// 区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
// 每个区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.menuArray.count;
}
// cell的设置
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuseID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseID];
    }
    if (indexPath.row == 0) {
        cell.imageView.image = [UIImage imageNamed:@"头像.png"];
        cell.textLabel.textColor = [UIColor whiteColor];
    }
    
    cell.textLabel.text = self.menuArray[indexPath.row];
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.alpha = 0.5;
    if (indexPath.row == self.index) {
        cell.textLabel.alpha = 1;
    }
    cell.backgroundColor = [UIColor clearColor];
    
//    UIView *view = [[UIView alloc]initWithFrame:CGRectZero];
//    view.backgroundColor = [UIColor clearColor];
//    cell.selectedBackgroundView = view;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

// 每行的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 100;
    }
    return 50;
}
#pragma mark - UITableViewDelegate
//点击cell的响应事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //取消选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    self.index = indexPath.row;
    [tableView reloadData];
#warning 第三步：执行相关的协议方法
    //代理 传值
    if ([self.menuDelegate respondsToSelector:@selector(didClickMenuIndex:Title:)]) {
        [self.menuDelegate didClickMenuIndex:indexPath.row Title:self.menuArray[indexPath.row]];
    }
    //关闭抽屉
    [[CK_MenuViewController getMenuViewController] hideLeftViewController ];
    
}
#pragma mark - 头部视图
// 头部高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 1;
}
// 头部视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kMenuLeftWidth, 70)];
    self.leftTableView.tableHeaderView = headerView;
    
    //搜索按钮
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(0, 0, 50, headerView.frame.size.height);
    [searchBtn setImage:[UIImage imageNamed:@"search.jpg"] forState:UIControlStateNormal];
    [headerView addSubview:searchBtn];
    
    //下载按钮
    UIButton *downLoadBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    downLoadBtn.frame = CGRectMake(searchBtn.frame.origin.x + kMenuLeftWidth/4, 0, 50, headerView.frame.size.height);
    [downLoadBtn setImage:[UIImage imageNamed:@"downLoad.jpg"] forState:UIControlStateNormal];
    [headerView addSubview:downLoadBtn];
    
    //喜欢按钮
    UIButton *hobbyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    hobbyBtn.frame = CGRectMake(downLoadBtn.frame.origin.x + kMenuLeftWidth/ 4, 0, 50, headerView.frame.size.height);
    [hobbyBtn setImage:[UIImage imageNamed:@"hobby.jpg"] forState:UIControlStateNormal];
    [headerView addSubview:hobbyBtn];
    
    //其它
    UIButton *otherBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    otherBtn.frame = CGRectMake(hobbyBtn.frame.origin.x + kMenuLeftWidth / 4, 0, 50, headerView.frame.size.height);
    [otherBtn setImage:[UIImage imageNamed:@"other.jpg"] forState:UIControlStateNormal];
    [headerView addSubview:otherBtn];
    return headerView;
}
#pragma mark - 尾部视图
// 尾部视图的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
